using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace ShowSubSites
{
    [Guid("72d27820-3088-495e-a343-ce76a0655d6c")]
    public class ShowSubSites : System.Web.UI.WebControls.WebParts.WebPart
    {
        public string _CSSStyle = "";
        public ShowSubSites()
        {
            this.ExportMode = WebPartExportMode.All;
        }
        [Personalizable, WebBrowsable, WebDisplayName("CSS Style")]
        public string Set_CSSStyle
        {
            get
            {
                return _CSSStyle;
            }
            set
            {
                _CSSStyle = value;
            }
        }
        private string text = "";
        SPWeb currentSite = null;

        public string SubSitesInHTMLTable
        {
            get
            {
                StringBuilder builder = new StringBuilder();
                text = "";
                currentSite = SPControl.GetContextWeb(Context);
                SPWebCollection subSites = currentSite.GetSubwebsForCurrentUser();

                builder.Append(@"<table border='0' width='100%'>");

                foreach (SPWeb site in subSites)
                {
                    builder.Append("<tr><td class='");
                    builder.Append(_CSSStyle);
                    builder.Append("'>");
                    builder.Append("<a href='");
                    builder.Append(site.Url);
                    builder.Append("'title=''>");
                    builder.Append(site.Title);
                    builder.Append("</a></td></tr>");
                }
                builder.Append("</table>");
                return builder.ToString();
            }
            set
            {
                text = value;
            }
            
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                writer.WriteLine(SubSitesInHTMLTable);
            }
            catch (Exception ex)
            {
                writer.WriteLine("There was an error. Please contact your system administrator with the following error message " + ex.Message);
            }
            finally
            {
                if (currentSite != null)
                    currentSite.Dispose();
            }
        }
    }
}
